﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
//using Blacklight.Controls;
using VAdvantage.Utility;
using System.Data;
using VAdvantage.DataBase;
using System.ComponentModel;
using VAdvantage.Model;
using VAdvantage.Panels;
using VAdvantage.Grids;
//using VAdvantage.ViewModels;
using VAdvantage.WorkSpace;
using SL4PopupMenu;
using VAdvantage.NewMailService;
//using VAdvantage.Extensions;
using VAdvantage.Classes;
////using VAdvantage.Views;
//using SlEmail.Extensions;
//using Microsoft.Practices.Prism.Commands;

using System.Windows.Browser;
using System.Text;
using VAdvantage.MailBox.Classes;
using System.Collections.ObjectModel;

namespace VAdvantage.Apps
{
    public partial class BusinessActivity : CFrame
    {
        /** MWindow for AccountCombination  */
        private GridWindow _mWindow = null;
        /** MTab for AccountCombination     */
        private GridTab _mTab = null;
        /** GridController                  */
        private GridController _gridController = null;
        /** Window No					*/
        private int _windowNo;






        object form = null;

        public BusinessActivity()
            : base(Msg.GetMsg("BusinessActivity"))
        {
            InitializeComponent();

            this.FormState = SilverlightDesktop.Common.FormState.Maximized;

            itemBusinessActivities.Header = Msg.GetMsg("MyBusinessActivities");

            base.SetTitle(Msg.GetMsg("BusinessActivity"));

            //itemBusinessActivities.Content = tabBusy;
            //tabBusy.IsBusy = true;
            LoadRoleCenterTabs();

            Grid.SetRow(gridBusy, 1);
            Grid.SetColumn(gridBusy, 0);
            RightPanelGrid.Children.Add(gridBusy);

            //if(item5.IsExpanded)
            //LoadViewModel();

            //Create Action list on load to resolve problem of not opening Action list first time on press image button
            CreateActionList();


            imgHeader.Source = Envs.LoadImageSource("MyContact.png");
            string msg = Msg.GetMsg("MyBusinessActivities");
            lblHeader.Content = msg;
            Envs.SetBusyIndicator(false);
        }



        //MainViewModel mainViewModel = null;

        //void LoadViewModel()
        //{
        //    UserInformation info = null;
        //    SmtpUserInformation smtpUserInfo = null;
        //    BackgroundWorker bgw = new BackgroundWorker();
        //    bgw.DoWork += (ov, ev) =>
        //    {
        //        info = UserInformationExtensions.UserInformation;
        //        smtpUserInfo = UserInformationExtensions.SmtpUserInformation;
        //    };

        //    bgw.RunWorkerCompleted += (ov, ev) =>
        //    {
        //        if (info != null)
        //            mainViewModel = new MainViewModel(info);
        //    };

        //    bgw.RunWorkerAsync();
        //}

        #region RoleCenter

        List<KeyNamePair> itemsList = new List<KeyNamePair>();  //stores all the items in list of keyname pair
        Dictionary<int, MImage> lstMImage = new Dictionary<int, MImage>();    //stores all the images associated with role center tabs
        List<int> lstTabID = new List<int>();   //stores tab ids only
        List<KeyNamePair> tabList = new List<KeyNamePair>();

        /// <summary>
        /// Loads the tab in Business Activities Tab
        /// </summary>
        void LoadRoleCenterTabs()
        {
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (ev, ov) =>
            {
                //load tab query
                String SQL = @"SELECT rcm.Name,
                      rct.Name,
                      rct.AD_Image_ID, rct.RC_RoleCenterTab_ID
                    FROM rc_rolecentermanager rcm
                    INNER JOIN RC_RoleCenterTab rct
                    ON rcm.RC_RoleCenterManager_ID = rct.RC_RoleCenterManager_ID 
                    where rcm.IsActive = 'Y' AND rcm.AD_Role_ID = " + Envs.GetCtx().GetAD_Role_ID() + " ORDER BY rct.SeqNo";

                //tabList.Clear();
                IDataReader dr = DB.ExecuteReader(SQL);
                if (dr != null)
                {
                    while (dr.Read())
                    {
                        int id = int.Parse(dr["RC_RoleCenterTab_ID"].ToString());
                        tabList.Add(new KeyNamePair(int.Parse(dr["RC_RoleCenterTab_ID"].ToString()), dr[1].ToString()));
                        lstTabID.Add(id);
                        string name = dr[1].ToString();
                        KeyNamePair items = new KeyNamePair(id, name);
                        itemsList.Add(items);

                        int temp = 0;
                        if (!dr[2].ToString().Equals(""))
                            temp = int.Parse(dr[2].ToString());

                        MImage image = MImage.Get(Envs.GetCtx(), temp);
                        lstMImage.Add(id, image);
                    }
                }
            };

            bgw.RunWorkerCompleted += (ov, ev) =>
            {


                for (int i = 0; i < itemsList.Count; i++)
                {
                    Grid grid = new Grid();

                    Image image = new Image();
                    image.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    image.Height = 20;
                    image.Width = 20;

                    TextBlock text = new TextBlock();
                    text.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    text.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                    text.FontSize = 12;
                    text.TextWrapping = TextWrapping.Wrap;
                    text.Margin = new Thickness(23, 0, 0, 0);
                    text.FontSize = 12;
                    text.Foreground = new SolidColorBrush(Colors.White);
                    text.FontWeight = FontWeights.Normal;

                    text.Text = itemsList[i].GetName();
                    text.Tag = itemsList[i].GetKey();

                    grid.Children.Add(image);
                    grid.Children.Add(text);

                    byte[] data = (lstMImage[itemsList[i].GetKey()] as MImage).GetBinaryData();
                    if (data != null)
                        image.Source = (lstMImage[itemsList[i].GetKey()] as MImage).GetImage();
                    else
                        image.Source = Envs.LoadImageSource("DefaultWindow.png");

                    ListBoxItem listboxtitem = new ListBoxItem();
                    listboxtitem.Padding = new Thickness(7);
                    //listboxtitem.Margin = new Thickness(20, 0, 0, 0);
                    listboxtitem.Content = grid;
                    listboxtitem.Tag = itemsList[i].GetKey() + "#" + itemsList[i].GetName();
                    listboxtitem.MouseLeftButtonUp += new MouseButtonEventHandler(listboxtitem_MouseLeftButtonUp);

                    lstBusinessActivitiesList.Items.Add(listboxtitem);

                }

            };

            bgw.RunWorkerAsync();
        }

        int CurrentActiveID = 0;
        BusyIndicator gridBusy = new BusyIndicator();

        List<int> ViewedTabs = new List<int>();
        FramePaneView fpw = null;
        ListBoxItem listboxtitem = null;
        void listboxtitem_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            listboxtitem = (sender as ListBoxItem);
            string[] values = listboxtitem.Tag.ToString().Split('#');
            int id = int.Parse(values[0]);
            string lName = values[1];

            lblHeader.Content = lName;

            if (id.Equals(CurrentActiveID))
            {
                centerPaneGrid.Visibility = Visibility.Collapsed;
                schedularGrid.Visibility = System.Windows.Visibility.Collapsed;

                scrollPanels.Visibility = System.Windows.Visibility.Visible;

                return;
            }

            byte[] data = (lstMImage[id] as MImage).GetBinaryData();
            if (data != null)
                imgHeader.Source = (lstMImage[id] as MImage).GetImage();
            else
                imgHeader.Source = Envs.LoadImageSource("DefaultWindow.png");

            //lblHeader.Content = 
            gridBusy.Style = Application.Current.Resources["RoundBusyIndicator"] as Style;
            gridBusy.IsBusy = true;

            if (fpw == null)
                fpw = new FramePaneView(false);

            fpw.AddTabToList(tabList);

            bool iscached = false;
            Grid grid = fpw.LoadGridData(id, CurrentActiveID, gridBusy, scrollPanels, out iscached);

            //gridBusy.IsBusy=false;
            scrollPanels.Visibility = Visibility.Visible;
            //scrollPanels.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
            scrollPanels.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            scrollPanels.Content = grid;

            if (!iscached)
            {
                fpw.LoadTabPanels(id);
            }
            CurrentActiveID = id;

        }
        #endregion

        PopupMenu menu = new PopupMenu();







        private void SetCenterPane(UIElement control)
        {
            //scrollPanels.Content = null;
            scrollPanels.Visibility = System.Windows.Visibility.Collapsed;
            schedularGrid.Visibility = System.Windows.Visibility.Collapsed;
            centerPaneGrid.Children.Clear();
            centerPaneGrid.Children.Add(control);
            centerPaneGrid.Visibility = System.Windows.Visibility.Visible;
        }


        PopupMenu infoWin = null;

        private void CreateActionList()
        {

            if (infoWin != null)
            {
                return;

            }

            infoWin = new PopupMenu();
            PopupMenuItem mnu = new PopupMenuItem(null, Msg.GetMsg(Envs.GetCtx(), "AddView"), null);
            mnu.ImageSource = Envs.LoadImageSource("AddView22.png");
            mnu.Name = "AddView";
            mnu.Click += (ov, ev) =>
            {
                if (fpw != null)
                    fpw.AddFrame();
            };
            infoWin.AddItem(mnu);


            mnu = new PopupMenuItem(null, Msg.GetMsg(Envs.GetCtx(), "AddChart"), null);
            mnu.ImageSource = Envs.LoadImageSource("AddChart22.png");
            mnu.Name = "AddChart";
            mnu.Click += (ov, ev) =>
            {
                if (fpw != null)
                    fpw.AddChart();
            };

            infoWin.Items.Add(mnu);

            mnu = new PopupMenuItem(null, Msg.GetMsg(Envs.GetCtx(), "AddKPI"), null);
            mnu.ImageSource = Envs.LoadImageSource("AddKPIPane22.png");
            mnu.Name = "AddKPIPane";
            mnu.Click += (ov, ev) =>
            {
                if (fpw != null)
                    fpw.AddKPI();
            };

            infoWin.Items.Add(mnu);

            infoWin.AddSeparator();

            mnu = new PopupMenuItem("Images/ResetCacheX32.png", Msg.GetMsg(Envs.GetCtx(), "ResetCache"), null);
            mnu.ImageSource = Envs.LoadImageSource("ResetCache22.png");
            mnu.Name = "ResetCache";
            mnu.Click += (ov, ev) =>
            {
                if (fpw != null)
                {
                    fpw.Reset();

                    if (listboxtitem != null)
                    {
                        CurrentActiveID = 0;
                        listboxtitem_MouseLeftButtonUp(listboxtitem, null);
                    }
                }
            };

            infoWin.Items.Add(mnu);

            infoWin.AddTrigger(TriggerTypes.LeftClick, image1);
            //infoWin.AddTrigger(TriggerTypes.LeftClick, label1);
        }

        void mnuFrame_Click(object sender, RoutedEventArgs e)
        {

        }

        void mnu_Click(object sender, RoutedEventArgs e)
        {
            //if (form is MyContact)
            //{
            //    contact.Refresh();
            //}
            //if (form is MyActivity)
            //{
            //    activity.Refresh();
            //}
        }

        void mnuChart_Click(object sender, RoutedEventArgs e)
        {
            VAdvantage.Scheduler.AppointmentForm AppForm = new Scheduler.AppointmentForm(0, 0, true);
            AppForm.Show();
        }

        public void SetBusy(bool value)
        {
            //this.IsEnabled = !value;
            //busyWindow.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            //txtBusy.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }

        private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        /// <summary>
        /// Business Activities process
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void itemBusinessActivities_IsExpandedChanged(object sender, AccordionItem.sel PropertyChangedEventArgs<bool> e)
        //{
        //if (itemBusinessActivities.IsExpanded)
        //{
        //    //scrollPanels.Visibility = Visibility.Visible;
        //    centerPaneGrid.Visibility = Visibility.Collapsed;
        //    schedularGrid.Visibility = System.Windows.Visibility.Collapsed;


        //    image1.Visibility = System.Windows.Visibility.Visible;
        //    label1.Visibility = System.Windows.Visibility.Visible


        //}
        //else
        //{
        //    image1.Visibility = System.Windows.Visibility.Collapsed;
        //    label1.Visibility = System.Windows.Visibility.Collapsed;
        //}
        //}

        private void itemBusinessActivities_Selected(object sender, RoutedEventArgs e)
        {
            if (itemBusinessActivities.IsSelected)
            {
                //scrollPanels.Visibility = Visibility.Visible;
                centerPaneGrid.Visibility = Visibility.Collapsed;
                schedularGrid.Visibility = System.Windows.Visibility.Collapsed;
                image1.Visibility = System.Windows.Visibility.Visible;
                label1.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                image1.Visibility = System.Windows.Visibility.Collapsed;
                label1.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        string GetLine(Dictionary<string, string> d)
        {
            // Build up each line one-by-one and them trim the end
            StringBuilder builder = new StringBuilder();
            foreach (KeyValuePair<string, string> pair in d)
            {
                builder.Append(pair.Key).Append(":").Append(pair.Value).Append(',');
            }
            string result = builder.ToString();
            // Remove the final delimiter
            result = result.TrimEnd(',');
            return result;
        }

        private void OpenRecordWindow(string winName, string primaryKeyCol, int primaryKey)
        {
            VAdvantage.Apps.AWindow win = new VAdvantage.Apps.AWindow();
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                int AD_Window_ID = win.GetWindowID(winName);		// hardcoded

                Dispatcher.BeginInvoke(delegate
                {

                    if (AD_Window_ID <= 0)
                    {
                        return;
                    }
                    bool showWin = win.InitWindow(AD_Window_ID, VAdvantage.Classes.Query.GetEqualQuery(primaryKeyCol, Convert.ToInt32(primaryKey)));//  int.Parse(ctrl.Rows[ctrl.CurrentRow.Index].Cells[primaryKey].Value.ToString())));
                    //if (showWin)
                    //    win.Show();
                });
            });
        }


        /// <summary>
        /// mail on business partner or user contact
        /// </summary>
        /// <param name="tableID"></param>
        /// <param name="fromMail"></param>
        /// <returns></returns>
        private DataTable Zoom(int tableID, string fromMail)
        {
            IDataReader idr = null;
            String _sql = "SELECT TableName FROM AD_TABLE WHERE AD_TABLE_ID=" + tableID;
            object tableName = VAdvantage.DataBase.DB.ExecuteScalar(_sql);
            string sql = "SELECT " + tableName + "_ID " + " , C_BPartner_ID " + "FROM " + tableName + " WHERE  lower(Email) =" + "'" + fromMail.Trim().ToLower() + "'";
            idr = VAdvantage.DataBase.DB.ExecuteReader(MRole.GetDefault(VAdvantage.Utility.Envs.GetCtx(), false).AddAccessSQL(sql, tableName.ToString(), MRole.SQL_NOTQUALIFIED, MRole.SQL_RO));//+ " order by ad_texttemplate_id");                    
            DataTable dt = new DataTable();
            dt.Load(idr);
            idr.Close();
            return dt;
        }











        private void DummyRectForDoubleClick_Loaded(object sender, RoutedEventArgs e)
        {
            //GraphicsUtils.DoubleClickHandler dblClickHandler = new GraphicsUtils.DoubleClickHandler(ListBoxItem_DoubleClick);
            // GraphicsUtils gu = new GraphicsUtils();
            // gu.AttachDoubleClick(sender, dblClickHandler);
        }

        private void image1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {

        }


    }

}
